package com.ad.pet.app.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.ad.pet.App;
import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.RxDisposable;
import com.ad.pet.app.login.fragment.AccountLoginContract;
import com.ad.pet.app.login.fragment.AccountLoginPresenter;
import com.ad.pet.common.data.utils.SpUtil;
import com.ad.pet.common.data.utils.glide.GlideUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.events.Events;
import com.ad.pet.common.structure.events.RxBus;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.AppToolbarActivity;
import com.ad.pet.constant.Constant;
import com.ad.pet.models.remote.User;
import com.ad.pet.ui.InputView;
import com.jakewharton.rxbinding.widget.RxTextView;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;

/**
 * Created by SEELE on 2019/6/27.
 */

public class ThirdBindActivity extends AppToolbarActivity implements MobileInputContract.View, AccountLoginContract.View {

    String openId;
    String thirdId;
    String imageUrl;
    @Inject
    AccountLoginPresenter mAccountPresenter;

    @Inject
    MobileInputPresenter mMobileInputPresenter;
    @BindView(R.id.input_account)
    InputView inputAccount;
    @BindView(R.id.input_phone_code)
    InputView inputPhoneCode;
    @BindView(R.id.input_pwd)
    InputView inputPwd;
    @BindView(R.id.iv_pic_code)
    ImageView ivPicCode;
    @BindView(R.id.input_invate_code)
    InputView inputInvate;
    @BindView(R.id.btn_commit)
    Button btnCommit;
    @BindView(R.id.iv_head)
    ImageView mIvHead;
    boolean isCanCode = true;
    private boolean isEye;
    @Inject
    RxDisposable mRxDisposable;
    private String uniqueId;
    private String nickName;

    @BindView(R.id.relate_code)
    RelativeLayout relativeLayoutPassword;

    @Override
    protected void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        mStatusLayoutManager.showContent();

        ;
    }

    @Override
    protected int contentLayout() {
        return R.layout.activity_third_login;
    }

    @Override
    protected void clickRetry(View v) {

    }

    @Override
    protected void initViews() {
        inputInvate.setVisibility(View.GONE);
        relativeLayoutPassword.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        mMobileInputPresenter.onCreate(this);
        mAccountPresenter.onCreate(this);
        thirdId = getIntent().getStringExtra("Third_id");
        imageUrl = getIntent().getStringExtra("image_url");
        nickName = getIntent().getStringExtra("nickname");
        uniqueId = getIntent().getStringExtra("uniqueId");
        openId = getIntent().getStringExtra("openid");
        GlideUtil.loadCircle(mActivity, imageUrl, mIvHead);
    }

    @Override
    protected void initEvents() {
        mRxDisposable.add(RxTextView.textChanges(inputAccount.getEtContent()).subscribe(new Action1<CharSequence>() {
            @Override
            public void call(CharSequence charSequence) {
                if (charSequence.length() == 11) {
                    mMobileInputPresenter.checkPhone(inputAccount.getContent());
                }
            }
        }));
        ivPicCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isEye = !isEye;
                setEye();
            }
        });

        inputPhoneCode.getTvRight().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(inputAccount.getContent())) {
                    ToastUtil.getToastUtil().showShort(inputAccount.getEtContent().getHint().toString());
                    return;
                }
                if (isCanCode) {
                    isCanCode = false;
                    mAccountPresenter.getEmailCode(inputAccount.getContent(), "4", "60", "2");
                }
            }
        });
        btnCommit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(inputAccount.getContent())) {
                    ToastUtil.getToastUtil().showShort(inputAccount.getEtContent().getHint().toString());
                    return;
                }

                if (TextUtils.isEmpty(inputPhoneCode.getContent())) {
                    ToastUtil.getToastUtil().showShort(inputPhoneCode.getEtContent().getHint().toString());
                    return;
                }

                if (TextUtils.isEmpty(inputPwd.getContent())&&relativeLayoutPassword.getVisibility()==View.VISIBLE) {
                    ToastUtil.getToastUtil().showShort(inputPwd.getEtContent().getHint().toString());
                    return;
                }
                if ((inputPwd.getContent().length() < 6 || inputPwd.getContent().length() > 16)&&relativeLayoutPassword.getVisibility()==View.VISIBLE) {
                    ToastUtil.getToastUtil().showShort("密码请输入6-16个字符");
                    return;
                }

                mMobileInputPresenter.thirdLogin(inputAccount.getContent(), inputPhoneCode.getContent(), inputPwd.getContent(), thirdId, nickName, imageUrl, uniqueId, inputInvate.getContent());


            }
        });
    }

    @Override
    public void initInject() {
        DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build().inject(this);
    }

    @Override
    protected BasePresenter getPresenter() {
        return mMobileInputPresenter;
    }


    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {
        ToastUtil.getToastUtil().showShort(msg);

    }

    @Override
    public void checkPhoneSuccess(int isRegist) {
        if (isRegist == 0) {

            inputInvate.setVisibility(View.VISIBLE);
            relativeLayoutPassword.setVisibility(View.VISIBLE);
        } else {

            inputInvate.setVisibility(View.GONE);
            relativeLayoutPassword.setVisibility(View.GONE);

        }
        btnCommit.setText("确定");
    }

    @Override
    public void checkBindThirdSuccess(User user) {

    }

    @Override
    public void checkBindUnBind() {

    }

    @Override
    public void thirdLoginSuccess(User user) {


        SpUtil.getInstance().putString(Constant.ACCESS_TOKEN, user.getToken());
        SpUtil.getInstance().putString(Constant.USER_ID, user.getUser_name());
        App.username = user.getUser_name();
        App.phone = user.getUser_tel();
        ToastUtil.getToastUtil().showShort(getString(R.string.login_success));
        RxBus.getDefault().post(new Events.AddCarts());
        RxBus.getDefault().post("third_bind_success");
        RxBus.getDefault().post("set_message_number_success");
//        Map loginMap = new HashMap();
//        loginMap.put("userid", LyxUtils.md5(user.getAccess_token(), "e828854e53b93a3b1e19c4cab2de707a"));
//        MobclickAgent.onEvent(mActivity, "__login", loginMap);

        Intent intent = new Intent();
        intent.putExtra("goHome", 0);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void error(int code, String msg) {
        ToastUtil.getToastUtil().showShort(msg);
        isCanCode = true;
    }

    @Override
    public void phoneLoginSuccess(User user) {

    }

    @Override
    public void accountLoginSuccess(User user) {

    }

    @Override
    public void getEmailCodeSuccess() {
        ToastUtil.getToastUtil().showShort("获取验证码成功");
        mRxDisposable.add(Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
                .take(59)
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        isCanCode = false;
                        String format = String.format("%ds", 60 - aLong);
                        RxTextView.text(inputPhoneCode.getTvRight()).call(format);
                    }

                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                }, new Action0() {
                    @Override
                    public void call() {
                        isCanCode = true;
                        RxTextView.text(inputPhoneCode.getTvRight()).call(getString(R.string.get_phone_verify_code));


                    }
                }));
    }

    @Override
    public void forgetPwdResetSuccess() {

    }

    @Override
    public void resetPwdSuccesss() {

    }

    @Override
    public void registJpushSuccess() {

    }

    private void setEye() {

        if (isEye) {
            ivPicCode.setImageResource(R.drawable.ic_eye);
            inputPwd.getEtContent().setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            ivPicCode.setImageResource(R.drawable.ic_uneye);
            inputPwd.getEtContent().setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

    }
}
